namespace SilverSea.Untilities
{
    using Microsoft.Win32;
    using System;
    using System.Globalization;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;

    public static class SystemUntils
    {
        public static string dateSeparator = "/";
        public static string decimalSymbol = ".";
        public static string programName = string.Empty;
        public static string shortDateFormat = "MM/dd/yyyy";
        public static string thousandSymbol = ",";
        public static string timeFormat = "HH:mm:ss";
        public static string timeSeparator = ":";

        public static void GetCurrentSystemSettings()
        {
            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\International", true);
                dateSeparator = key.GetValue("sDate").ToString();
                shortDateFormat = key.GetValue("sShortDate").ToString();
                timeSeparator = key.GetValue("sTime").ToString();
                timeFormat = key.GetValue("sTimeFormat").ToString();
                decimalSymbol = key.GetValue("sDecimal").ToString();
                thousandSymbol = key.GetValue("sThousand").ToString();
                key.Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show("An error occur while load system settings: " + exception.Message);
            }
        }

        [DllImport("kernel32.dll", SetLastError=true)]
        private static extern int GetLocalTime(ref SystemTime systemTime_0);
        [DllImport("kernel32.dll", SetLastError=true)]
        private static extern int GetSystemTime(ref SystemTime systemTime_0);
        public static bool IsAdministator()
        {
            return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
        }

        public static bool IsProgramInstalled(string programName)
        {
            try
            {
                string name = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(name))
                {
                    foreach (string str2 in key.GetSubKeyNames())
                    {
                        using (RegistryKey key2 = key.OpenSubKey(str2))
                        {
                            if ((key2.GetValue("DisplayName") != null) && key2.GetValue("DisplayName").ToString().ToLower().Contains(programName.ToLower()))
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
            return false;
        }

        [PermissionSet(SecurityAction.LinkDemand, XML="<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\">\r\n<IPermission class=\"System.Security.Permissions.RegistryPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\r\nversion=\"1\"\r\nWrite=\"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\"/>\r\n</PermissionSet>\r\n")]
        public static bool IsProgramStartWithWindows(string programName)
        {
            try
            {
                bool flag = false;
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                flag = key.GetValue(programName) != null;
                key.Close();
                return flag;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                return false;
            }
        }

        public static string RemoveUnicode(string s)
        {
            string str = s.Normalize(NormalizationForm.FormD);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                if (CharUnicodeInfo.GetUnicodeCategory(str[i]) != UnicodeCategory.NonSpacingMark)
                {
                    builder.Append(str[i]);
                }
            }
            return builder.ToString().Normalize(NormalizationForm.FormC);
        }

        public static void SetCurrentSystemSetting()
        {
            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\International", true);
                key.SetValue("sDate", dateSeparator);
                key.SetValue("sShortDate", shortDateFormat);
                key.SetValue("sTime", timeSeparator);
                key.SetValue("sTimeFormat", timeFormat);
                key.SetValue("sDecimal", decimalSymbol);
                key.SetValue("sThousand", thousandSymbol);
                key.Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show("An error occur while save system setting file: " + exception.Message);
            }
        }

        [DllImport("kernel32.dll", SetLastError=true)]
        public static extern int SetLocalTime(ref SystemTime lpSystemTime);
        [PermissionSet(SecurityAction.LinkDemand, XML="<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\">\r\n<IPermission class=\"System.Security.Permissions.RegistryPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\r\nversion=\"1\"\r\nWrite=\"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\"/>\r\n</PermissionSet>\r\n")]
        public static bool SetProgramStartWithWindows(string programName, bool autoStartWithWindows)
        {
            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                if (autoStartWithWindows)
                {
                    key.SetValue(programName, "\"" + Application.ExecutablePath + "\"");
                }
                else if (key.GetValue(programName) != null)
                {
                    key.DeleteValue(programName);
                }
                key.Close();
                return true;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                return false;
            }
        }

        public static void SetStandardSystemSetting()
        {
            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\International", true);
                key.SetValue("sDate", "/");
                key.SetValue("sShortDate", "MM/dd/yyyy");
                key.SetValue("sTime", ":");
                key.SetValue("sTimeFormat", "HH:mm:ss");
                key.SetValue("sDecimal", ".");
                key.SetValue("sThousand", ",");
                key.Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show("An error occur while save system setting file: " + exception.Message);
            }
        }

        public static void SetSystemDateTime(DateTime datetime)
        {
            SystemTime lpSystemTime = new SystemTime {
                wDay = (short) datetime.Day,
                wMonth = (short) datetime.Month,
                wYear = (short) datetime.Year,
                wHour = (short) datetime.Hour,
                wMinute = (short) datetime.Minute,
                wSecond = (short) datetime.Second
            };
            SetLocalTime(ref lpSystemTime);
        }

        [DllImport("kernel32.dll", SetLastError=true)]
        private static extern int SetSystemTime(ref SystemTime systemTime_0);
        public static void UpdateKey(string keys, string values)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load(Application.StartupPath + @"\" + programName + ".exe.config");
                foreach (XmlNode node2 in document.SelectSingleNode("configuration/appSettings"))
                {
                    if (node2.Attributes["key"].Value == keys)
                    {
                        node2.Attributes["value"].Value = values;
                    }
                }
                document.Save(Application.StartupPath + @"\" + programName + ".exe.config");
                document.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            }
            catch (Exception exception)
            {
                MessageBox.Show("An error occur while update App.config: " + exception.Message);
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SystemTime
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }
    }
}

